const express = require('express')
const router = express.Router()
const jwt=require('jsonwebtoken')
const SECRET_KEY='login2022'

const mysql= require('mysql')
const db=require('../db/db')
const connection = mysql.createConnection(db.mysqlConfig)
connection.connect((err)=>{
    if(err) throw err;
    console.log("连接成功")
})
router.post('/login', (req, res) => {
    // console.log(req.body)
    const name=req.body.name
    const password=req.body.password
    let sql=`select name,password from user where name='${name}' and password='${password}'`
    // console.log(sql)
    const token=jwt.sign(
        {user:{name:name,password:password}},
        SECRET_KEY,
        {expiresIn: '3h'}
    )
    // console.log(token)


    connection.query(sql,(err,result)=>{
        let dataString=JSON.stringify(result);
        let data=JSON.parse(dataString);
        // console.log(data)
        if(data.length==0){
            res.json({
                status:'201',
                msg:'用户名或者密码错误'
            })
        }else{

            res.json({
                status:'200',
                msg:'登录成功',
                data:data,
                token
            })
        }
    })
})
module.exports=router